#!/usr/bin/env python3

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

img = cv.imread("../pic/7.png")
icon = cv.imread("../pic/icon.png")

# logo放在左上角，所以我创建了ROI
rows, cols, channels = icon.shape
roi = img[0:rows, 0:cols]
plt.subplot(341), plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB)), plt.title('ORIGINAL')
plt.subplot(342), plt.imshow(cv.cvtColor(icon, cv.COLOR_BGR2RGB)), plt.title('ICON')
plt.subplot(343), plt.imshow(cv.cvtColor(roi, cv.COLOR_BGR2RGB)), plt.title('ROI')

# 现在创建logo的掩码，并同时创建其相反掩码
icongray = cv.cvtColor(icon, cv.COLOR_BGR2GRAY)
ret, mask = cv.threshold(icongray, 100, 255, cv.THRESH_BINARY)
mask_inv = cv.bitwise_not(mask)
plt.subplot(344), plt.imshow(icongray, "gray"), plt.title('icongray')
plt.subplot(345), plt.imshow(mask, "gray"), plt.title('mask')
plt.subplot(346), plt.imshow(mask_inv, "gray"), plt.title('mask_inv')

# 现在将ROI中logo的区域涂黑
img_bg = cv.bitwise_and(roi, roi, mask=mask_inv)
plt.subplot(347), plt.imshow(cv.cvtColor(img_bg, cv.COLOR_BGR2RGB)), plt.title('img_bg')

# 仅从logo图像中提取logo区域
icon_fg = cv.bitwise_and(icon, icon, mask=mask)
plt.subplot(348), plt.imshow(cv.cvtColor(icon_fg, cv.COLOR_BGR2RGB)), plt.title('icon_fg')

# 将logo放入ROI并修改主图像
dst = cv.add(img_bg, icon_fg)
plt.subplot(349), plt.imshow(cv.cvtColor(dst, cv.COLOR_BGR2RGB)), plt.title('dst')

img[0:rows, 0:cols] = dst
plt.subplot(3, 4, 10), plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB)), plt.title('img')
plt.show()

cv.destroyAllWindows()
